/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TCPSocket;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

/**
 *
 * @author David de Hoop
 */
public class ExportCSV {
    
	// Instance variabeles for export to CSV.
	String FileName;
    JSONObject SensorsJSON;
    JSONObject AlarmsJSON;
    String SensorsString;
    
	// Counter increment for generateCsvFile (w) and generateAlarmCsv (w2)
	int w = 0;
    int w2= 0;
    
	// Linked HashMap to save sensornames and ArrayLists with sensorvalues, sorted ascending.
    private Map<String, List<Double>> hashMap = new LinkedHashMap<>();
    private Map<String, List<String>> hashMap2 = new LinkedHashMap<>();
    
	// ipadress and portnumber for server
    String ipadress = "145.92.78.217";
    int portnumber = 81;
   
   String jsonString;
            
    String Sensorname;
    String Alarmname;
    
    double SensorValue;
    String AlarmValue;
   
   // Adds sensorvalues to LinkedList in HashMap, only one LinkedList per sensor.
   private void addSensorValueToMap(String sensorName, double value) {
        if (hashMap.get(sensorName) == null) {
            // This sensor doesn't have a list in the map yet.
            hashMap.put(sensorName, new LinkedList<Double>());
        }
        // Get the list belonging to this sensor and add the value
        hashMap.get(sensorName).add(value);
   }
   
   // Adds alarms to the LinkedList in HashMap, only one LinkedList per alarmname.
   private void addAlarmValueToMap(String alarmName, String value) {
        if (hashMap2.get(alarmName) == null) {
            // This sensor doesn't have a list in the map yet.
            hashMap2.put(alarmName, new LinkedList<String>());
        }
        // Get the list belonging to this sensor and add the value
        hashMap2.get(alarmName).add(value);
   }
   
   // Generates a file containing comma seperated values
   public void generateCsvFile() throws IOException
   {
	   // Specify filepath for .csv file.
       FileWriter writer = new FileWriter("c:\\test.csv");
       
        writer.append("name");
	    writer.append(',');
	    writer.append("min");
        writer.append(',');
	    writer.append("max");
        writer.append(',');
	    writer.append("avg");
        writer.append('\n');
       
       Socket TCPSocket = new Socket(ipadress, portnumber);
       TCPSocket.setKeepAlive(true);
        
       DataInputStream inFromServer = new DataInputStream(TCPSocket.getInputStream());
       BufferedReader br = new BufferedReader(new InputStreamReader(inFromServer, "UTF-8"));
             
       while(w < 5) {
           jsonString = br.readLine();
           SensorsJSON = (JSONObject) JSONSerializer.toJSON(jsonString);  
           JSONArray AnalogArray =  (JSONArray) SensorsJSON.get("analogSensors");
           
       if(SensorsJSON.get("analogSensors") != null) {    
       for (int i = 0; i < AnalogArray.size(); i++) {
           JSONObject jsonObject = AnalogArray.getJSONObject(i);
           Sensorname = (jsonObject.get("name").toString());
           SensorValue = (double) jsonObject.get("value");
           
           addSensorValueToMap(Sensorname, SensorValue);
       }
       w++;
       }
       else {}
       }
                 
       Iterator<Map.Entry<String, List<Double>>> iterator =
                hashMap.entrySet().iterator();
        
        while (iterator.hasNext()) {
            Map.Entry<String, List<Double>> entry = iterator.next();
            
            String sensorName = entry.getKey();
            
            List<Double> sensorValues = entry.getValue();
            Collections.sort(sensorValues);
            double min = Math.round(sensorValues.get(0) * 100) / 100;
            double max = Math.round(sensorValues.get((sensorValues.size()-1))*100) / 100;
            double add = 0;
            
            for (int i2 = 0; i2 < sensorValues.size(); i2++) {
            add = add+sensorValues.get(i2);
            }
            double avg = Math.round((add / sensorValues.size())*100) / 100;
            
            writer.append(sensorName);
            writer.append(", ");
            writer.append(String.valueOf(min));
            writer.append(", ");
            writer.append(String.valueOf(max));
            writer.append(", ");
            writer.append(String.valueOf(avg));
            writer.append('\n');
        }  
    	    writer.flush();
	    writer.close();
   
   }
   
   public void generateAlarmCsv() throws IOException{
       
          FileWriter writer = new FileWriter("c:\\testAlarms.csv");
       
            writer.append("name");
	    writer.append(',');
	    writer.append("alarmName");
            //writer.append('\n');
       
       Socket TCPSocket = new Socket(ipadress, portnumber);
       TCPSocket.setKeepAlive(true);
        
       DataInputStream inFromServer = new DataInputStream(TCPSocket.getInputStream());
       BufferedReader br = new BufferedReader(new InputStreamReader(inFromServer, "UTF-8"));
             
       while(w2 < 20) {
           jsonString = br.readLine();
           AlarmsJSON = (JSONObject) JSONSerializer.toJSON(jsonString);  
           JSONObject Alarms = (JSONObject) AlarmsJSON.get("alarm"); 
           
           if(AlarmsJSON.get("alarm") != null) {    
           Alarmname = (Alarms.get("name").toString());
           AlarmValue = (String) Alarms.get("alarmName");
           
           addAlarmValueToMap(Alarmname, AlarmValue);
           }
           else{}
       w2++;
       }
       
       
       Iterator<Map.Entry<String, List<String>>> iterator =
                hashMap2.entrySet().iterator();
        
        while (iterator.hasNext()) {
            Map.Entry<String, List<String>> entry = iterator.next();
            
            String alarmName = entry.getKey();
            
            List<String> alarmValues = entry.getValue();
                       
            writer.append(alarmName);
            writer.append(", ");
            writer.append(String.valueOf(alarmValues));
           // writer.append('\n');
        }  
    	    writer.flush();
	    writer.close();
   
   }
         
//public static void main(String[] args) throws IOException {
//        ExportCSV test = new ExportCSV();
//        test.generateAlarmCsv();
//}
}